package com.hkrt.demo.data.repository

import com.hkrt.demo.data.cache.MemoryCache
import com.hkrt.demo.data.mapper.Mapper
import com.hkrt.demo.data.network.ApiConstants
import com.hkrt.demo.data.network.HkrtApiService
import com.hkrt.demo.data.response.LoginResponse
import com.hkrt.demo.domain.entity.Comment
import com.hkrt.demo.domain.entity.Like
import com.hkrt.demo.domain.entity.Shot
import com.hkrt.demo.domain.fetcher.result_listener.RequestType
import com.hkrt.demo.domain.repository.HkrtRepository
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.functions.Consumer

/**
* @author  Chenjinguang
* @date 02.08.2017.
*/
class HkrtDataRepository(private var hkrtApiService: HkrtApiService,
                         private val memoryCache: MemoryCache,
                         private val mapper: Mapper) : HkrtRepository {

    override fun getShotList(shotType: String, count: Int): Flowable<List<Shot>> {
        val requestType = if (shotType == ApiConstants.TYPE_POPULAR)
            RequestType.POPULAR_SHOTS
        else
            RequestType.RECENT_SHOTS

        return if (memoryCache.hasCacheFor(requestType)) {
            Flowable.fromCallable<List<Shot>> { memoryCache.getCacheForType(requestType) }
        } else {
            hkrtApiService.getShots(shotType, count)
                    .map { mapper.translate(it) }
                    .doOnNext { memoryCache.put(requestType, it) }
        }
    }

    override fun getShotLikes(shotId: String): Flowable<List<Like>> {
        return hkrtApiService.getShotLikes(shotId)
                .map { mapper.translate(it) }
    }

    override fun getShotComments(shotId: String): Single<List<Comment>> =
            if (memoryCache.hasCacheFor(RequestType.COMMENTS)) {
                Single.fromCallable<List<Comment>> { memoryCache.getCacheForType(RequestType.COMMENTS) }
            } else {
                hkrtApiService.getShotComments(shotId)
                        .map { mapper.translate(it) }
                        .doOnSuccess { memoryCache.put(RequestType.COMMENTS, it) }
            }

    override fun likeShot(shotId: String) = hkrtApiService.likeShot(shotId)

    override fun deleteCacheFor(requestType: RequestType) {
        memoryCache.clearCacheFor(requestType)
    }

    override fun login(params:HashMap<String,String>): Flowable<LoginResponse> {
        return hkrtApiService.login(params).map { it ->
            mapper.translate(it)
        }
    }
//                .doOnNext {
//                    if (it.code.equals("00")) {
//                        preferences.setUserLoggedIn()
//                        saveUserInfo(loginResponse)
//                    } else {
//                        throw  ApiException (it.code, it.msg)
//                    }
//                }
//                .doOnNext(loginResponse -> {

//        });
}